package com.ba.base.view

import android.content.Context
import android.util.AttributeSet
import android.view.LayoutInflater
import android.widget.LinearLayout
import androidx.core.widget.addTextChangedListener
import com.ba.base.R
import kotlinx.android.synthetic.main.layout_code_input.view.*

class CodeInputView @JvmOverloads constructor(
    context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0
) : LinearLayout(context, attrs, defStyleAttr) {

    private var completeCallback: ((code: String) -> Unit)? = null

    init {
        LayoutInflater.from(context).inflate(R.layout.layout_code_input, this, true)
        this.et_code_1.addTextChangedListener(
            onTextChanged = { _, _, _, _ ->
                if (et_code_1.text.length == 1) {
                    this.et_code_2.setText("")
                    this.et_code_3.setText("")
                    this.et_code_4.setText("")
                    this.et_code_2.requestFocus()
                }
            }
        )
        this.et_code_2.addTextChangedListener(
            onTextChanged = { _, _, _, _ ->
                if (et_code_2.text.length == 1) {
                    this.et_code_3.setText("")
                    this.et_code_4.setText("")
                    this.et_code_3.requestFocus()
                }
            }
        )
        this.et_code_3.addTextChangedListener(
            onTextChanged = { _, _, _, _ ->
                if (et_code_3.text.length == 1) {
                    this.et_code_4.setText("")
                    this.et_code_4.requestFocus()
                }
            }
        )

        this.et_code_4.addTextChangedListener(
            onTextChanged = { _, _, _, _ ->
                if (et_code_1.text.isEmpty()) {
                    et_code_1.requestFocus()
                    return@addTextChangedListener
                }
                if (et_code_2.text.isEmpty()) {
                    et_code_2.requestFocus()
                    return@addTextChangedListener
                }
                if (et_code_3.text.isEmpty()) {
                    et_code_3.requestFocus()
                    return@addTextChangedListener
                }
                if (et_code_4.text.isNotEmpty()) {
                    val code = String.format(
                        "%s%s%s%s",
                        et_code_1.text.toString(),
                        et_code_2.text.toString(),
                        et_code_3.text.toString(),
                        et_code_4.text.toString()
                    )
                    completeCallback?.invoke(code)

                }
            }
        )
    }

    fun setOnCompleteListener(callback: ((code: String) -> Unit)?) {
        this.completeCallback = callback
    }

}